﻿using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using LinqToTwitter;
using Sitecore.Data.Fields;
using Sitecore.Web;
using Sitecore.Web.UI.WebControls;
using System;

namespace TweetFeed.Sublayouts
{

	public partial class Widget : System.Web.UI.UserControl
	{
		public string UserProfileImage { get; set; }
		public string ProfileFullName { get; set; }
		public string ProfileUserName { get; set; }
		public string ProfileTweetCount { get; set; }
		public string ProfileFollowingCount { get; set; }
		public string ProfileFollowersCount { get; set; }
		public bool ShowProfileImages { get; set; }

		private void Page_Load(object sender, EventArgs e)
		{
			if (IsPostBack)
				return;

			if (Sitecore.Context.PageMode.IsPageEditorEditing)
				litEditHeadline.Text = "TweetFeed Widget";

			InitializeList();

		}

		private void InitializeList()
		{
			if(((Sublayout)Parent != null))
			{
				var rawParameters = ((Sublayout) Parent).Parameters;

				if (!string.IsNullOrWhiteSpace(rawParameters))
				{
					var widgetSettings = WebUtil.ParseUrlParameters(rawParameters);

					if (widgetSettings != null)
					{
						var settingsReference = widgetSettings[Authentication.Settings];
						var authentication = Authentication.GetSingleUserAuthorizer(Sitecore.Context.Database.GetItem(settingsReference));

						var widgetType = widgetSettings[Authentication.WidgetType];
						var count = 5; 
						int.TryParse(widgetSettings[Authentication.StatusCount],out count);
						ShowProfileImages = widgetSettings[Authentication.ShowImage] == "1";

						var searchTerm = widgetSettings[Authentication.SearchTerm];


						if (!string.IsNullOrWhiteSpace(searchTerm) && count > 0)
						{
							switch (widgetType)
							{
								case "Profile":
									
									pnlSearch.Visible = true;
									pnlProfile.Visible = true;
									var profileName = searchTerm;
									var profile = GetProfile(profileName, authentication);
									var profileTweets = GetProfileTweets(profile, count, authentication);
									if (profile != null && profileTweets != null)
									{
										UserProfileImage = profile.ProfileImageUrlHttps;
										ProfileFullName = profile.Name;
										ProfileUserName = profile.ScreenName;
										ProfileTweetCount = profile.StatusesCount.ToString();
										ProfileFollowingCount = profile.FriendsCount.ToString();
										ProfileFollowersCount = profile.FollowersCount.ToString();

										rptTweets.DataSource = profileTweets;
										rptTweets.DataBind();
									}
									break;

								case "Search":
									pnlSearch.Visible = true;
									pnlProfile.Visible = false;

									var term = searchTerm;

									var tweets = GetSearchTweets(term, count, authentication);
									if (tweets != null)
									{
										rptTweets.DataSource = tweets;
										rptTweets.DataBind();
									}
									break;
							}
						}
						else
						{
							litMessage.Text = "<br />Please configure the widget";
						}
					}
				}
				else
				{
					litMessage.Text = "<br />Please configure the widget";
				}
			}
		}

		private List<Status> GetSearchTweets(string searchTerm, int count, SingleUserAuthorizer authentication)
		{
			try
			{
				var tContext = new TwitterContext(authentication);
				var query = from tweets in tContext.Search
				            where tweets.Type == SearchType.Search && tweets.Query == searchTerm
				            select tweets;

				return query.Single().Statuses.Take(count).ToList();
			}
			catch (TwitterQueryException e)
			{

				litMessage.Text = "<br />Error while searching Twitter";
				Sitecore.Diagnostics.Log.Error("Error while querying Twitter",e,this);
				return null;
			}
		}

		private List<Status> GetProfileTweets(User profile, int count, SingleUserAuthorizer authentication)
		{
			try
			{
				var tContext = new TwitterContext(authentication);
				var query = from tweets in tContext.Status
				            where tweets.Type == StatusType.User && tweets.ScreenName == profile.ScreenName
				            select tweets;

				return query.Take(count).ToList();
			}
			catch (TargetInvocationException e)
			{
				
				litMessage.Text ="<br />Error while querying profile tweets";
				Sitecore.Diagnostics.Log.Error("Error while querying profile tweets", e, this);
				return null;
			}
		}

		private User GetProfile(string profileName, LinqToTwitter.SingleUserAuthorizer authentication)
		{
			try
			{
				var tContext = new TwitterContext(authentication);
				var query = from usr in tContext.User
				            where usr.Type == UserType.Show && usr.ScreenName == profileName
				            select usr;

				return query.SingleOrDefault();

			}

			catch (TwitterQueryException e)
			{

				var response = ((WebException)e.InnerException).Response as HttpWebResponse;
				switch (response.StatusCode)
				{
					case HttpStatusCode.NotFound:
						litMessage.Text = "Profile not found";
						Sitecore.Diagnostics.Log.Warn("Profile not found", this);
						break;

						case HttpStatusCode.OK:
						break;

						default:
						litMessage.Text = "<br />Error while querying Twitter";
						Sitecore.Diagnostics.Log.Error("Error while querying Twitter",e,this);
						break;
				}

				return null;

			}
		}
	}
}